package com.example.demo.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author Rocket
 * @version 10.0.1
 * @date 2021-08-08 2:22 PM
 */
@WebServlet(name="online users", urlPatterns = {"/users"})
public class OnlineUsers extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getSession().getId();
        ServletContext application = req.getServletContext();
        List<String> usersList = (List<String>) application.getAttribute("usersList");
        if(usersList == null) {
            usersList = new ArrayList<>();
            application.setAttribute("usersList", usersList);
        }
        if(!usersList.contains(id)) {
            usersList.add(id);
        }

        for(String str : usersList) {
            resp.getWriter().println(str);
        }


        resp.getWriter().println("Total online users are : " + usersList.size());

    }
}
